/**
 * Copyright (c) 2015-2030 by Beijing Yanlight Co., Ltd.
 * All rights reserved.
 */
package com.yanlight.util;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.springframework.util.CollectionUtils;

/**
 * 
 * @author haolw
 * @time 2018/02/27
 */
public abstract class DevSignatureUtil {
	private final static String SIGN_KEY = "sign";
	private final static String NONCESTR_KEY = "nonceStr";

	/**
	 * 加密
	 * 
	 * @param paramsMap
	 * @param secret
	 * @return
	 */
	public static String sign(Map<String, String> paramsMap, String secret) {
		if (CollectionUtils.isEmpty(paramsMap)) {
			return null;
		}
		List<String> keys = new ArrayList<String>(paramsMap.keySet());
		List<String> content = new ArrayList<String>(paramsMap.keySet().size() + 1);
		Collections.sort(keys);
		for (String key : keys) {
			String value = paramsMap.get(key);
			if (StringUtils.isNoneBlank(key, value)) {
				content.add(key + "=" + value);
			}
		}
		content.add("key=" + secret);
		String txt = StringUtils.join(content, "&");
		return EncryptUtil.md5(txt);
	}

	/**
	 * 验签
	 * 
	 * @param httpRequest
	 * @param secret
	 * @return
	 */
	public static boolean verify(HttpServletRequest httpRequest, String secret) {
		String fromSign = httpRequest.getParameter(SIGN_KEY);
		String nonceStr = httpRequest.getParameter(NONCESTR_KEY);
		if (StringUtils.isAnyBlank(fromSign, nonceStr)) {
			return false;
		}
		if (nonceStr.length() > 32) {
			return false;
		}
		Enumeration<String> parameterNames = httpRequest.getParameterNames();
		Map<String, String> paramsMap = new HashMap<String, String>(16);
		while (parameterNames.hasMoreElements()) {
			String key = parameterNames.nextElement();
			if (!SIGN_KEY.equals(key)) {
				String value = httpRequest.getParameter(key);
				paramsMap.put(key, value);
			}
		}
		String sign = sign(paramsMap, secret);
		return sign.equals(fromSign);
	}

}
